package com.cloudbroker.bcs.platform.dav.common.ext.annotation;

import com.alibaba.fastjson.JSON;
import com.cloudbroker.bcs.common.util.NetworkUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 * Created by dengwei06015 on 2016/1/19.
 */
@Aspect
@Component
public class LogContract {
    private static final Logger logger = LoggerFactory.getLogger(LogContract.class);

    @Before("within(@org.springframework.stereotype.Controller *) && @annotation(saveLog)")
    public void beforeExecute(final JoinPoint joinPoint, SaveLog saveLog) {
        try {
            saveLog(saveLog, null);
        } catch (Exception e) {
            logger.error("发生异常: ", e);
        }
    }

    @AfterReturning(pointcut = "within(@org.springframework.stereotype.Controller *) && @annotation(saveLog)", returning = "returnValue")
    public void afterExecute(final JoinPoint joinPoint, SaveLog saveLog, Object returnValue) {
        try {
            saveLog(saveLog, returnValue);
        } catch (Exception e) {
            logger.error("发生异常: ", e);
        }
    }

    private void saveLog(SaveLog saveLog, Object returnValue) throws IOException {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar ca = Calendar.getInstance();
        String operTime = df.format(ca.getTime());
        String ip = NetworkUtil.getIpAddress(request);
        String remark = saveLog.remark();
        String uri = request.getRequestURI();
        String params = JSON.toJSONString(request.getParameterMap(), true);
        if (returnValue == null) {
            logger.info("\r\n发送-------------->" + operTime + "\t" + uri + "\t" + ip + "\t" + remark + "\t" + params.replaceAll("password=\\w*,", "password=******,"));
        } else {
            logger.info("\r\n返回-------------->" + operTime + "\t" + uri + "\t" + ip + "\t" + remark + "\t" + returnValue.toString().replaceAll("password=\\w*,", "password=******,"));
        }
    }

}
